package main

import (
	"fmt"
	"time"
)

func main() {
	timeObj := time.Now()
	fmt.Println(timeObj) // 2024-12-22 14:32:18.8922488 +0800 CST m=+0.000000001
  year := timeObj.Year() // 2024
  month := timeObj.Month() // 12
  day := timeObj.Day() // 22
  hour := timeObj.Hour() // 14
  minute := timeObj.Minute() // 32
  second := timeObj.Second() // 18
	fmt.Printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute: %d, Second: %d\n", year, month, day, hour, minute, second)

	// 格式化时间
	fmt.Println(timeObj.Format("2006-01-02 15:04:05")) // 2024-12-22 14:32:18 string 24小时制
	fmt.Println(timeObj.Format("2006-01-02 03:04:05")) // 2024-12-22 14:32:18.892248800 +0800 CST m=+0.000000001 string 12小时制
	fmt.Println(timeObj.Format("2006-01-02")) // 2024-12-22
	fmt.Println(timeObj.Format("15:04:05")) // 14:32:18
	fmt.Println(timeObj.Format("15:04")) // 14:32

	unixTime := timeObj.Unix() // 获取当前时间戳 纳秒：UnixNano()
	fmt.Println(unixTime)
	// 时间戳转时间
	timeObj2 := time.Unix(unixTime, 0) //要求转换的时int64类型
	// 转毫秒就在第一个地方写unixTime 转纳秒就在第二个地方写unixTime
	fmt.Println(timeObj2)

	// 日期字符串转时间戳
	var timeStr = "2024-12-22 14:32:18"
	timeObj3, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local)
	fmt.Println(timeObj3)
	fmt.Println(timeObj3.Unix()) // 1640195938
	
	fmt.Println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

	// 时间操作函数
	timeObj4 := time.Now()
	fmt.Println("timeObj4:", timeObj4)
	timeObj4 = timeObj4.Add(time.Hour * 24) // 加24小时
	fmt.Println("timeObj4:", timeObj4)
	timeObj4 = timeObj4.AddDate(0, 0, -7) // 减7天
	//                           年 月 日
	fmt.Println("timeObj4:", timeObj4)

	// 定时器
	ticker := time.NewTicker(time.Second * 2) // 每隔2秒触发一次
	n := 5
	for t := range ticker.C {
		n--
		if n == 0 {
			ticker.Stop() // 停止定时器
			break
		}
		fmt.Println("ticker:", t)
	}

	// 延时
	fmt.Println("delay 2 seconds...")
	time.Sleep(time.Second * 2) // 延时2秒
	fmt.Println("delay 2 seconds...done")
}